package com.sxproject.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import com.sxproject.pojo.dto.UsersPageQueryDTO;
import com.sxproject.pojo.dto.UsersDto;
import com.sxproject.pojo.entity.Users;
import com.sxproject.mapper.UsersMapper;
import com.sxproject.pojo.vo.UsersVo;
import com.sxproject.result.PageResult;
import com.sxproject.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-11-17
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Override
    public PageResult<UsersVo> pageQuery(UsersPageQueryDTO usersPageQueryDTO) {
        //开始分页查询
        // 设置分页相关参数
        Page<Users> page = Page.of(usersPageQueryDTO.getPage(), usersPageQueryDTO.getPageSize());

        Page<Users> p = lambdaQuery()
                .like(usersPageQueryDTO.getNickname() != null, Users::getNickname, usersPageQueryDTO.getNickname())
                .like(usersPageQueryDTO.getRegion() != null, Users::getRegion, usersPageQueryDTO.getRegion())
                .eq(usersPageQueryDTO.getId() != null, Users::getId, usersPageQueryDTO.getId())
                .page(page);

        PageResult<UsersVo> pageResult = new PageResult<UsersVo>();
        pageResult.setTotal(p.getTotal());
        List<Users> records = p.getRecords();
        List<UsersVo> usersvo =new ArrayList<>();
        if (records == null){
            pageResult.setRecords(Collections.emptyList());
            return pageResult;
        }
        for (Users user : records) {
            UsersVo usersVo = new UsersVo();
            BeanUtils.copyProperties(user,usersVo);
            usersvo.add(usersVo);
        }
        pageResult.setRecords(usersvo);
        // 返回分页查询结果
        return pageResult;
    }

    @Override
    public void saveAdd(UsersDto usersDto) {
        Users users = new Users();
        BeanUtils.copyProperties(usersDto,users);
        users.setCreatedAt(LocalDateTime.now());
        users.setUpdatedAt(LocalDateTime.now());
        users.setStatus(0);
        save(users);
    }

    @Override
    public void update(UsersDto usersDto) {
        Users users = new Users();
        BeanUtils.copyProperties(usersDto,users);
        users.setUpdatedAt(LocalDateTime.now());
        updateById(users);
    }
}
